<?php

class ZFPainel_Bootstrap extends Zend_Application_Module_Bootstrap
{

    protected $responders = array();
    protected $acl;

    public function _initPainel()
    {
        if (!isset($_SERVER['REQUEST_URI'])) {
            return true;
        }

        if (substr($_SERVER['REQUEST_URI'], 0, 7) != '/painel') {
            return true;
        }

        $this->_initAuth();

        $this->_initRouterTela();

        if (substr($_SERVER['REQUEST_URI'], 0, 12) == '/painel/tela') {
            //$this->_initRouterTela();
        } else {
            $this->_apiInitFrontController();
            $this->_apiInitControllerAction();
        }
    }

    private function _apiInitFrontController()
    {
        $frontController = Zend_Controller_Front::getInstance();

        $frontController->setRequest(new REST_Request);
        $frontController->setResponse(new REST_Response);

//        if (TRUE !== ZC_Config::getInstance()->getVarApiOn()) {
//            $frontController->getResponse()->unauthorized();
//            $frontController->getResponse()->sendHeaders();
//            exit;
//        }
        // add the REST route for the API module only
        $restRoute = new Zend_Rest_Route($frontController, array(
            'format' => 'json',
                ), $this->responders);
        $frontController->getRouter()->addRoute('apiRouter', $restRoute);

        $frontController->registerPlugin(new REST_Controller_Plugin_RestHandler($frontController));
    }

    private function _apiInitControllerAction()
    {
        // add REST contextSwitch helper
        $contextSwitch = new ZFKiller_Controller_Action_Helper_ContextSwitch();
        Zend_Controller_Action_HelperBroker::addHelper($contextSwitch);

        // add restContexts helper
        $restContexts = new REST_Controller_Action_Helper_RestContexts();
        Zend_Controller_Action_HelperBroker::addHelper($restContexts);
    }

    private function _initRouterTela()
    {
        $router = Zend_Controller_Front::getInstance()->getRouter();
        $router->addRoute('RotaTela', new ZFPainel_Controller_Router_Route_Tela());
    }

    private function _initAuth()
    {
        Zend_Controller_Front::getInstance()
                ->registerPlugin(new ZFPainel_Controller_Plugin_Auth(array(
                    'acl' => $this->acl,
                )))
        ;
    }

    public function _initErrorSwitcher()
    {
        Zend_Controller_Front::getInstance()
                ->registerPlugin(new ZFKiller_Controller_Plugin_ErrorControllerSwitcher())
        ;
    }

}
